<template>
  <view class="friend-box">
    <uni-nav-bar @clickLeft="clickLeft" :title="navTitle" fixed statusBar :border="false" :backgroundColor="backgroundColor">
      <template #left>
        <view class="u-center left-bg">
          <img src="https://img.qumoyugo.com/webimgbg/pet-icon-arrow-left-nav-b.png" style="width:9px;
          height: 17px">
        </view>
      </template>
    </uni-nav-bar>
    <view class="wrapper-frd">
      <view class="content-box">
        <view class="process">
          <view class="title-box u-center">
            <view style="padding:0 16rpx">邀请流程</view>
          </view>
          <view class="step-icon u-center">
            <view class="item">
              <img src="https://img.qumoyugo.com/webimgbg/picopino-pet-activit-proc-step1.png" class="img">
              <view>发出邀请</view>
              <view class="tips">&nbsp;</view>
            </view>
            <view class="li-b">
              <view class="line"></view>
            </view>
            <view class="item">
              <img src="https://img.qumoyugo.com/webimgbg/picopino-pet-activit-proc-step2.png" class="img">
              <view>好友首次登录</view>
              <view class="tips">&nbsp;</view>
            </view>
            <view class="li-b">
              <view class="line"></view>
            </view>
            <view class="item">
              <img src="https://img.qumoyugo.com/webimgbg/picopino-pet-activit-proc-step3.png" class="img">
              <view class="u-center">
                <img src="https://img.qumoyugo.com/webimgbg/picopino_icon_activit_yaoqing_ok.png" style="width:24rpx ;height:25rpx;margin-right:10rpx">
                邀请成功
              </view>
              <view class="tips">获得小饼干奖励</view>
            </view>
          </view>
        </view>
        <view class="count-box">
          <view class="title-box u-center">
            <view style="padding:0 16rpx">奖励统计</view>
            <view class="mx-jl" @click="gotoPage('/user/inviteList')">
              <view class="u-center">
                <view style="margin-bottom:2px;font-size:11px">奖励明细</view>
                <uni-icons type="right" color="#000" size="14"></uni-icons>
              </view>
            </view>
          </view>
          <view class="num-box">
            <view class="half">
              <view class="size">
                {{ recommendInfo.recommendUserNum }}
              </view>
              <view>邀请用户</view>
            </view>
            <view class="half">
              <view class="u-center">
                <view class="size">
                  <!-- {{ recommendInfo.accumulatedCookies ? format(recommendInfo.accumulatedCookies) : '—' }} -->
                  {{ recommendInfo.accumulatedCookies && format(recommendInfo.accumulatedCookies) }}
                </view>
              </view>
              <view>获得小饼干</view>
            </view>
          </view>
        </view>
        <view class="yaoq-btn" @click="() => popupShare.open()">去邀请</view>
        <view class="rules-box">
          <view style="font-weight:bold;margin-bottom:24rpx">邀请有礼规则</view>
          <rich-text class="rich-val" :nodes="recommendInfo.rule"></rich-text>
        </view>
      </view>
    </view>
    <uni-popup ref="popupShare" type="bottom" background-color="none" :safe-area="false" @maskClick="closeShare">
      <view class="liji-it">
        <view class="cont">
          <button open-type="share" class="natv-button-3" v-if="customerId">
            <img src="https://img.qumoyugo.com/webimgbg/pet-activit-share-wx-n.png" class="img">
            <view>好友邀请</view>
          </button>
          <button class="natv-button-3" v-else @click="gotoPage(`/pages/login?redirect=${encodeURIComponent('/user/friend')}`)">
            <img src="https://img.qumoyugo.com/webimgbg/pet-activit-share-wx-n.png" class="img">
            <view>好友助力</view>
          </button>
          <button class="natv-button-3" @click="generatePoster">
            <img src="https://img.qumoyugo.com/webimgbg/pet-activit-share-pic-n.png" class="img">
            <view>扫码邀请</view>
          </button>
        </view>
        <view class="top-img" :style="{transform: popupPoster ? 'translate(-50%, 0)' : 'translate(-50%, 200%)'}">
          <image :src="imagePostUrl" style="width:100%;height:100%" show-menu-by-longpress></image>
        </view>
        <view class="btn-box-share u-center">
          <view class="btn u-center" @click="closePoster">取消</view>
          <view class="btn download u-center" @click="saveImage" v-if="popupPoster">
            <img src="https://img.qumoyugo.com/webimgbg/picopino_icon_download_friend_nwlf.png" style="width:25rpx;height:22rpx;margin-right:10rpx">
            下载
          </view>
        </view>
      </view>
    </uni-popup>
    <!-- #ifdef MP-WEIXIN -->
    <canvas style="width: 660px;height: 880px;opacity: 0;" canvas-id="firstCanvas" id="canvasImg"></canvas>
    <!-- #endif -->
  </view>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted, computed } from 'vue'
import { onPageScroll, onShareAppMessage } from '@dcloudio/uni-app'
import { format, base64ToSave } from '@/utils/utils'
import { useStore } from '@/store'
const store = useStore()
const _this = getCurrentInstance()
const { $https } = _this.appContext.config.globalProperties
const backgroundColor = ref('transparent')
const navTitle = ref('')
const popupPoster = ref(null)
const popupShare = ref(null)
const recommendInfo = ref({})
const tempQRIMG = ref('')
const imagePostUrl = ref('')
onPageScroll((e) => {
  if (e.scrollTop > 100) {
    backgroundColor.value = '#ffffff'
    navTitle.value = '邀请好友'
  } else {
    backgroundColor.value = 'transparent'
    navTitle.value = ''
  }
})
onMounted(() => {
  $https({
    url: '/recommend/index',
    type: 'ac'
  }).then(res => {
    if (res.code === 0) {
      recommendInfo.value = res.data
    }
  })
  $https({
    url: '/qr-code',
    type: '',
    data: {
      scene: 'mp4',
      page: 'share/sendFriend',
      param: `rmd=${customerId.value}&platform=MP&orgin=pico`
    }
  }).then(async res => {
    if (res.code === 0) {
      // #ifdef MP-WEIXIN
      const base64Url = 'data:image/png;base64,' + res.data
      const urlQR = await base64ToSave(base64Url)
      tempQRIMG.value = urlQR
      // #endif
    }
  })
})
onShareAppMessage(() => {
  return {
    title: recommendInfo.value.title || '请加入品客聚精彩，精彩伴你一起',
    path: `/share/sendFriend?rmd=${customerId.value}&platform=MP&orgin=pico`,
    imageUrl: 'https://img.qumoyugo.com/webimgbg/invite.jpeg'
  }
})
const customerId = computed(() => {
  return store.state.profile?.attr?.customerId || ''
})
const gotoPage = (url) => {
  uni.navigateTo({
    url
  })
}
const generatePoster = () => {
  if (!customerId.value) {
    gotoPage(`/pages/login?redirect=${encodeURIComponent('/user/friend')}`)
    return
  }
  if (imagePostUrl.value) {
    popupPoster.value = true
  } else {
    uni.showLoading({
      title: '海报生成中',
      mask: true
    })
    handleShareImgMp()
  }
}
// #ifdef MP-WEIXIN
const handleShareImgMp = async () => {
  const ctx = uni.createCanvasContext('firstCanvas')
  uni.downloadFile({
    url: 'https://img.qumoyugo.com/webimgbg/invite.jpeg',
    success: (res) => {
      if (res.statusCode === 200) {
        const x = 196
        const y = 560
        const width = 270
        const height = 270
        const cornerSize = 30
        ctx.rect(0, 0, 660, 880)
        ctx.setFillStyle('#F0831E')
        ctx.fill()
        // 话矩形
        ctx.beginPath()
        ctx.moveTo(x + cornerSize, y)
        ctx.arcTo(x + width, y, x + width, y + cornerSize, cornerSize)
        ctx.lineTo(x + width, y + height - cornerSize)
        ctx.arcTo(x + width, y + height, x + width - cornerSize, y + height, cornerSize)
        ctx.lineTo(x + cornerSize, y + height)
        ctx.arcTo(x, y + height, x, y + height - cornerSize, cornerSize)
        ctx.lineTo(x, y + cornerSize)
        ctx.arcTo(x, y, x + cornerSize, y, cornerSize)
        ctx.closePath()
        ctx.fillStyle = 'white'
        ctx.strokeStyle = 'black'
        ctx.fill()
        ctx.stroke()
        ctx.drawImage(res.tempFilePath, 0, 20, 660, 500)
        ctx.drawImage(tempQRIMG.value, 205, 570, 250, 250)
        ctx.draw(false, () => {
          uni.canvasToTempFilePath({
            canvasId: 'firstCanvas',
            success: (resF) => {
              uni.hideLoading()
              imagePostUrl.value = resF.tempFilePath
              popupPoster.value = true
            },
            fail: (res) => {
              console.log('生成失败', res)
              uni.hideLoading()
            }
          })
        })
      }
    },
    fail: (res) => {
      console.log('下载失败downloadFile', res)
    }
  })
}
// #endif
const closePoster = () => {
  if (popupPoster.value) {
    popupPoster.value = false
  } else {
    popupShare.value.close()
  }
}
const closeShare = () => {
  popupPoster.value = false
  popupShare.value.close()
}

// 保存图片
const saveImage = () => {
  wx.saveImageToPhotosAlbum({
    filePath: imagePostUrl.value,
    success: () => {
      uni.showToast({
        title: '已保存到相册',
        icon: 'none'
      })
    },
    fail: () => {
      console.log('erro')
    }
  })
}
//
const clickLeft = () => {
  uni.navigateBack({
    fail: () => {
      uni.switchTab({
        url: '/pages/eventsList'
      })
    }
  })
}
</script>

<style scoped lang="scss">
@import "@/assets/styles/minx.scss";
.friend-box{
  min-height: 100vh;
  background: url(https://img.qumoyugo.com/webimgbg/invite.jpeg) no-repeat #F0831E center 30rpx;
  background-size: 100%;
  .left-bg{
    width: 32px;
    height: 30px;
    border-radius: 50%;
    margin-top: 7px;
    padding-right: 2px;
  }
  .wrapper-frd{
    padding-top: 330rpx;
  }
  .content-box{
    padding: 0 30rpx 60rpx 30rpx;
  }
  .title-box{
    font-weight: bold;
    height: 66rpx;
    line-height: 66rpx;
    font-size: 30rpx;
    text-align: center;
    font-weight: bold;
    background-color: #FFF8E1;
    position: relative;
    color: #000;
  }
  .process{
    background: #FFFFFF;
    border-radius: 30rpx;
    font-size: 30rpx;
    color: #333333;
    margin-bottom: 20rpx;
    overflow: hidden;
  }
  .step-icon{
    justify-content: space-between;
    position: relative;
    text-align: center;
    font-size: 24rpx;
    line-height: 26rpx;
    padding: 40rpx 74rpx;
    font-weight: bold;
    white-space: nowrap;
    .img{
      width: 100rpx;
      height: 100rpx;
      margin-bottom: 10rpx;
    }
    .line{
      background: url('https://img.qumoyugo.com/webimgbg/picopino-pet-activit-line-bg-n.png') repeat-x center;
      height: 16rpx;
      background-size: 100%;
      width: 100rpx;
    }
    .li-b{
      width: 100rpx;
      height: 100rpx;
      align-self: flex-start;
      display: flex;
      align-items: center;
    }
    .tips{
      color: #F53F3F;
      font-size: 20rpx;
      font-weight: normal;
      margin-top: 10rpx;
    }
  }
  .liji-it{
    color: #000;
    font-size: 26rpx;
    background: #fff;
    border-radius: 30rpx 30rpx 0 0;
    position: relative;
    .cont{
      padding: 60rpx 176rpx;
      display: flex;
      justify-content: space-between;
      text-align: center;
    }
    .img{
      width: 80rpx;
      height: 80rpx;
      margin-bottom: 14rpx;
    }
    .btn-box-share{
      display: flex;
      text-align: center;
      font-size: 30rpx;
      color: #737373;
      padding: 20rpx 0 calc(20rpx + env(safe-area-inset-bottom)) 0;
      min-height: 70rpx;
      position: relative;
      &::before{
        @include border(top, #ddd)
      }
      .btn{
        width: 200rpx;
        height: 70rpx;
      }
      .download{
        border-radius: 1000px;
        background: #000;
        color: #F9C687;
        font-weight: bold;
      }
    }
    .top-img{
      position: absolute;
      width: 660rpx;
      height: 880rpx;
      bottom: calc(140rpx + env(safe-area-inset-bottom));
      border-radius: 30rpx;
      background-color: #F0831E;
      overflow: hidden;
      left: 50%;
      transform: translate(-50%, 200%);
      transition: all 0.5s;
    }
  }
  .count-box{
    background: #FFFFFF;
    border-radius: 30rpx;
    font-size: 30rpx;
    color: #333333;
    margin-bottom: 40rpx;
    overflow: hidden;
    .mx-jl{
      font-size: 22rpx;
      color: #000;
      position: absolute;
      top: 0;
      right: 24rpx;
      font-weight: normal;
    }
    .num-box{
      display: flex;
      justify-content: space-between;
      font-size: 24rpx;
      color: #000;
      line-height: 26px;
      text-align: center;
      padding: 30rpx 25rpx;
      .size{
        font-family: Arial, Helvetica, sans-serif;
        font-size: 50rpx;
        font-weight: bold;
      }
      .half{
        margin: 0 5rpx;
        border-radius: 20rpx;
        background: rgba(0, 0, 0, 0.04);
        flex: 1;
        padding: 40rpx 0;
      }
    }
  }
  .yaoq-btn{
    width: 407rpx;
    height: 103rpx;
    background: url(https://img.qumoyugo.com/webimgbg/picopino_activeit_yaoqing_bg_btn-l.png) no-repeat;
    background-size: 100%;;
    margin: 0 auto 50rpx auto;
    text-align: center;
    line-height: 102rpx;
    color: #FFF;
    font-size: 34rpx;
    font-weight: bold;
  }
  .rules-box{
    font-size: 24rpx;
    color: #000;
    padding: 0 32rpx 24rpx 32rpx;
  }
  .rich-val{
    word-break: break-all;
    white-space: pre-line;
  }
}

.natv-button-3 {
  margin: 0;
  padding: 0;
  background-color: transparent;
  border: none;
  font-size: 24rpx;
  line-height: 26rpx;
  &:after {
    border: none;
  }
}
#canvasImg {
  visibility: hidden;
  position: absolute;
  left: -200%;
  top: -300%;
}
</style>
